package com.lb.client;

import com.alibaba.fastjson.JSON;
import feign.Request;
import lombok.Data;
import org.slf4j.MDC;

import java.util.Optional;

import static com.lb.base.constants.BaseConstants.*;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Client 请求日志
 *
 * @author xiemingzhi
 * @since 1.0
 */
@Data
public class ClientLogRequest {
    /**
     * 客户端类型
     */
    private String type;
    /**
     * 请求类的方法
     */
    private String classMethod;
    /**
     * 请求地址
     */
    private String url;
    /**
     * 请求头
     */
    private String headers;
    /**
     * 请求体
     */
    private String body;
    /**
     * 链路编号
     */
    private String traceId;

    public static  ClientLogRequest build(String classMethod, Request request) {
        ClientLogRequest clientLogRequest = new ClientLogRequest();
        clientLogRequest.setClassMethod(classMethod);
        clientLogRequest.setUrl(request.url());
        clientLogRequest.setTraceId(MDC.get(MDC_KEY_TRACE_ID));
        clientLogRequest.setHeaders(JSON.toJSONString(request.headers()));
        byte[] body = request.body();
        if (request.body() != null) {
            clientLogRequest.setBody(new String(body, Optional.ofNullable(request.charset()).orElse(UTF_8)));
        }
        return clientLogRequest;
    }
}
